package com.xiaoyu.tool.controller.client.user;

import com.xiaoyu.tool.configuration.wx.WxMpProperty;
import com.xiaoyu.tool.entity.User.User;
import com.xiaoyu.tool.service.user.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 * @Author:xiaoyu
 * @Created on 2018/9/17
 * @Description 公众号网页授权登录
 */
@Controller    //@Controller 不是@RestController
@RequestMapping(value = "/webAuthorized")
@Slf4j
public class UserMpAuthorizedController extends BaseUserController{

    private final WxMpProperty wxMpProperty;

    private final WxMpService wxMpService;

    private final UserService userService;

    public UserMpAuthorizedController(WxMpProperty wxMpProperty, WxMpService wxMpService, UserService userService) {
        super(wxMpService);
        this.wxMpProperty = wxMpProperty;
        this.wxMpService = wxMpService;
        this.userService = userService;
    }


    /**
    *sdk 简单便捷
    */
    @ApiOperation("微信网页授权")
    @GetMapping("/authorize")
    public String welcome(){
        //授权成功后跳转同域名下的网页
        String returnUrl = wxMpProperty.getIndex();
        if (!StringUtils.isEmpty(getCurrentOpenId()) && !StringUtils.isEmpty(userService.findByOpenId(getCurrentOpenId()))){
            return "redirect:" + returnUrl;
        }
        //重定向的回调链接地址
        String url = wxMpProperty.getRedirectUri();
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        return "redirect:" + redirectUrl;
    }


    /**
     * 授权获取用户信息
     * */
    @ApiOperation("授权获取用户信息")
    @GetMapping("/oauth2")
    public String oauth2(@RequestParam(name = "code") String code,
                         @RequestParam("state") String returnUrl) {
        try {
            WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken,wxMpProperty.getLang());
            User user = userService.createAndUpdateUser(wxMpUser);
            setCurrentOpenId(user.getOpenId());
        } catch (Exception e) {
            log.error("获取用户信息失败:{}",e.getMessage());
        }
        return "redirect:" + returnUrl;
    }

}




